<template>
  <div class="app-container">
    <el-button type="primary" @click="handleAdd">添加商品</el-button>

    <el-table :data="productList" style="width: 100%;margin-top:30px;" stripe>
      <el-table-column 
        prop="name" 
        align="center" 
        label="名称">
      </el-table-column>
      <el-table-column 
        prop="code" 
        align="center" 
        label="编码">
      </el-table-column>
      <el-table-column 
        align="center" 
        label="图片">
        <template slot-scope="scope">
          <img :src="scope.row.pic" style="width: 100px; height: 100px" class="user-avatar">
        </template>
      </el-table-column>
      <el-table-column 
        prop="brandName" 
        align="center" 
        label="品牌">
      </el-table-column>
      <el-table-column 
        prop="productCategoryName" 
        align="center" 
        label="分类">
      </el-table-column>
      <el-table-column 
        prop="price" 
        align="center" 
        label="价格">
      </el-table-column>
      <el-table-column 
        prop="promotionPrice" 
        align="center" 
        label="促销价">
      </el-table-column>
      <el-table-column 
        prop="unit" 
        align="center" 
        label="单位">
      </el-table-column>
      <el-table-column 
        prop="weight" 
        align="center" 
        label="重量(克)">
      </el-table-column>
      <el-table-column 
        prop="stock" 
        align="center" 
        label="库存">
      </el-table-column>
      <el-table-column 
        prop="sale" 
        align="center" 
        label="销量">
      </el-table-column>
      <el-table-column 
        align="center" 
        label="是否上架">
        <template slot-scope="scope">{{ scope.row.publishStatus === 0 ? '下架' : '上架' }}</template>
      </el-table-column>
      <el-table-column 
        align="center" 
        label="是否推荐">
        <template slot-scope="scope">{{ scope.row.recommandStatus === 0 ? '否' : '是' }}</template>
      </el-table-column>

      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope)">编辑</el-button>
          <!-- <el-button type="text" size="small" @click="handleDetail(scope)">详情</el-button> -->
          <el-button type="text" size="small" @click="handlePublish(scope)">{{ scope.row.publishStatus === 0 ? '上架' : '下架' }}</el-button>
          <el-button type="text" size="small" @click="handleRecommand(scope)">{{ scope.row.recommandStatus === 0 ? '添加推荐' : '取消推荐' }}</el-button>
          <el-button type="text" size="small" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="block">
        <span class="demonstration"></span>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
    </div>

    <!-- 新增/编辑商品 -->
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑商品':'创建商品'">
      <el-form :model="product" label-width="80px" label-position="left">
        <el-form-item label="商品名称">
          <el-input v-model="product.name" placeholder="菜单名称" />
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:9527/aliyun/oss/upload"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="product.pic" :src="product.pic" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="品牌">
          <el-select v-model="product.brandId" filterable  placeholder="请选择">
            <el-option
              v-for="item in brandList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="product.productCategoryId" filterable  placeholder="请选择">
            <el-option
              v-for="item in productCategoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单价">
          <el-input v-model="product.price" placeholder="单价" />
        </el-form-item>
        <el-form-item label="赠送积分">
          <el-input v-model="product.giftPoint" placeholder="赠送积分" />
        </el-form-item>
        <el-form-item label="赠送成长值">
          <el-input v-model="product.giftGrowth" placeholder="赠送成长值" />
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model="product.stock" placeholder="库存" />
        </el-form-item>
        <el-form-item label="单位">
          <el-input v-model="product.unit" placeholder="单位" />
        </el-form-item>
        <el-form-item label="重量(克)">
          <el-input v-model="product.weight" placeholder="重量" />
        </el-form-item>
        <el-form-item label="是否上架">
            <el-radio v-model="product.publishStatus" label="0">否</el-radio>
            <el-radio v-model="product.publishStatus" label="1">是</el-radio>
        </el-form-item>
        <el-form-item label="是否推荐">
            <el-radio v-model="product.recommandStatus" label="0">否</el-radio>
            <el-radio v-model="product.recommandStatus" label="1">是</el-radio>
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input
            v-model="product.description"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="商品描述"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import path from 'path'
import { deepClone } from '@/utils'
import { getToken } from '@/utils/auth'
import { getBrandsAll } from '@/api/product'
import { getProductCategoriesAll } from '@/api/product'
import { getProducts, addProduct, getProductDetail, getProduct, updateProduct, updateProductDelete, updateProductesDelete, updateProductPublish, updateProductesPublish, updateProductRecommend, updateProductesRecommend } from '@/api/product'

const defaultRole = {
  key: '',
  name: '',
  description: '',
  routes: []
}

export default {
  data() {
    return {
      product: {
      },
      brandList: [],
      productCategoryList: [],
      productList: [],
      dialogVisible: false,
      dialogType: 'new',
      headers: {
        Authorization: ''
      },
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    // Mock: get all routes and roles list from server
    this.getProducts()
    this.getBrands()
    this.getProductCategories()
    this.headers.Authorization = getToken()
  },
  methods: {
    async getProducts() {
      const res = await getProducts(this.page)
      console.log("getProducts",res)

      const { pageNum, total, list} = res.data
      this.productList = list
      this.page.currentPage = pageNum
      this.page.total = total
    },
    async getBrands() {
      const res = await getBrandsAll()
      console.log("getBrandsAll",res)
      this.brandList = res.data
    },
    async getProductCategories() {
      const res = await getProductCategoriesAll()
      console.log("getProductCategories",res)
      this.productCategoryList = res.data
    },

    handleAdd() {
      // console.log("menu",this.menu)
      // console.log("menuAdd",this.menuAdd)
      this.product = {}
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    async handleEdit(scope) {
      const res = await getProduct(scope.row.id)
      console.log("handleEdit",res)
      this.product = res.data
      this.product.publishStatus = String(res.data.publishStatus)
      this.product.recommandStatus = String(res.data.recommandStatus)
      this.dialogType = 'edit'
      this.dialogVisible = true
    },
    handleDelete(scope) {
      this.$confirm('确认删除商品：'+scope.row.name+'?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await updateProductDelete(scope.row.id,1)
          this.$message({
            type: 'success',
            message: '删除商品成功'
          })
          this.getProducts()
        })
        .catch(() => { 
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
         })
    },
    handlePublish(scope) {
      const status = scope.row.publishStatus === 0 ? '上架' : '下架'
      this.$confirm('确认'+status+'商品：'+scope.row.name+'?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          if(status === '上架'){
            await updateProductPublish(scope.row.id,1).then(() => {
              this.$message({
                type: 'success',
                message: '已'+status+'商品'
              })
            })
          }else{
            await updateProductPublish(scope.row.id,0).then(() => {
              this.$message({
                type: 'success',
                message: '已'+status+'商品'
              })
            })
          }

          this.getProducts()
        })
        .catch(() => { 
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
         })
    },
    handleRecommand(scope) {
      const status = scope.row.recommandStatus === 0 ? '添加推荐' : '取消推荐'
      this.$confirm('确认'+status+'商品：'+scope.row.name+'?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          if(status === '添加推荐'){
            await updateProductRecommend(scope.row.id,1).then(() => {
              this.$message({
                type: 'success',
                message: '已'+status+'商品'
              })
            })
          }else{
            await updateProductRecommend(scope.row.id,0).then(() => {
              this.$message({
                type: 'success',
                message: '已'+status+'商品'
              })
            })
          }

          this.getProducts()
        })
        .catch(() => { 
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
         })
    },

    async confirmSubmit() {
      const isEdit = this.dialogType === 'edit'

      if (isEdit) {
        await updateProduct(this.product).then(() => {
          this.$message({
              type: 'success',
              message: '添加商品成功!'
            })
        })

      } else {
        await addProduct(this.product).then(() => {
          this.$message({
              type: 'success',
              message: '创建菜单成功!'
            })
        })

      }

      this.dialogVisible = false
      this.getProducts()

    },
    //logo上传
    handleAvatarSuccess(res, file) {
      console.log("上传成功回调",res,file)
      this.product.pic = res.data
      console.log(this.product)
    },
    beforeAvatarUpload(file) {
        // const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        // if (!isJPG) {
        //   this.$message.error('上传头像图片只能是 JPG 格式!');
        // }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isLt2M;
    },
    // reference: src/view/layout/components/Sidebar/SidebarItem.vue
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)

      // When there is only one child route, the child route is displayed by default
      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0]
        onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
        return onlyOneChild
      }

      // Show parent if there are no child route to display
      if (showingChildren.length === 0) {
        onlyOneChild = { ... parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
